<?php

class Application_Model_EventMapper {

    protected $_dbTable;

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_Event');
        }
        return $this->_dbTable;
    }

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Ungueltige Gateway-Klasse fuer Tabellendaten');
        }
        $this->_dbTable = $dbTable;
    }

    public function save(Application_Model_EventModel $event) {
        $data = array(
            'id' => $event->getId(),
            'date' => $event->getDate(),
            'location_id' => $event->getLocation_id(),
            'group_id' => $event->getGroup_id(),
        );
        if (null === $event->getId()) {
            unset($data['id']);

            $event->setId($this->getDbTable()->insert($data));
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $data['id']));
        }
        return $event;
    }

    public function find($id, Application_Model_EventModel $event) {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return null;
        }
        $row = $result->current();
        $event->setId($row['id'])
                ->setDate($row['date'])
                ->setLocation_id($row['location_id'])
                ->setgroup_id($row['group_id']);
        $locationRow = $row->findParentRow('Application_Model_DbTable_Location');
        $event->setLocationName($locationRow['name']);

        return $event;
    }

    public function fetchAll($where = null, $order = null, $count = null, $offset = null) {
        $resultSet = $this->getDbTable()->fetchAll($where, $order, $count, $offset);
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_EventModel();
            $entry->setId($row['id'])
                    ->setDate($row['date'])
                    ->setLocation_id($row['location_id'])
                    ->setgroup_id($row['group_id']);
            $locationRow = $row->findParentRow('Application_Model_DbTable_Location');
            $entry->locationName = $locationRow->name;

            $entries[] = $entry;
        }
        return $entries;
    }

    public function delete($eventId) {
        if ($eventId instanceof Application_Model_EventModel) {
            $eventId = $eventId->id;
        }
        return $this->getDbTable()->delete(array('id = ?' => $eventId));
    }

}

?>
